/*
 * @Author: WuFeng <763467339@qq.com>
 * @Date: 2022-03-22 12:12:49
 * @LastEditTime: 2023-03-27 15:04:58
 * @LastEditors: WuFeng <763467339@qq.com>
 * @Description: 登录用户信息
 * @FilePath: \vue3-element-plus-web\src\store\modules\user.js
 * @Copyright 版权声明
 */
import md5 from 'js-md5'
import {
  login,
  logout,
  getInfo,
  selectRole
} from '@/api/login'
import {
  getToken,
  setToken,
  removeToken,
  getUserType,
  setUserType,
  getLoginInfo,
  setLoginInfo,
  removeLoginInfo
} from '@/utils/auth'
import {
  removeStore
} from '@/plugins/store'
import store from '@/store/index'

const user = {
  state: {
    token: getToken(),
    userType: getUserType(), // 用户类型
    userInfo: {}, // 用户信息
    name: '',
    avatar: '',
    menus: [],
    menusLoad: false
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_USER_TYPE: (state, userType) => {
      state.userType = userType
    },
    SET_USERINFO: (state, userInfo) => {
      state.userInfo = userInfo
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_MENUS: (state, menus) => {
      state.menus = menus
      state.menusLoad = true
    }
  },

  actions: {
    // 登录
    Login({ commit }, { loginData, loginType, autoLogin = false }) {
      switch (loginType) {
        // 账号登录
        case 'ACCOUNT':
          return new Promise((resolve, reject) => {
            const loginName = loginData.loginName.trim()
            let password = ''
            const autoLoginInfo = getLoginInfo()
            const autoLoginEd = autoLoginInfo.autoLogin
            if (autoLoginEd === true) {
              const autoPassword = autoLoginInfo.password
              if (autoPassword === loginData.password.trim()) {
                password = loginData.password.trim()
              } else {
                password = md5(loginData.password.trim())
              }
            } else {
              password = md5(loginData.password.trim())
            }
            const code = loginData.code.trim()
            login(Object.assign({}, loginData, {
              loginName,
              password,
              code
            })).then((response) => {
              const data = response.data
              setToken(data)
              commit('SET_TOKEN', data)
              setUserType('ACCOUNT_LOGIN')
              commit('SET_USER_TYPE', 'ACCOUNT')
              // 自动登录缓存登录信息
              if (autoLogin === true) {
                setLoginInfo({
                  loginName,
                  password,
                  autoLogin
                })
              } else {
                removeLoginInfo()
              }
              resolve(response)
            }).catch((error) => {
              reject(error)
            })
          })
        // 短信验证码
        case 'MOBILE_NUMBER':
          return new Promise((resolve, reject) => {
            login(Object.assign({}, loginData, {
              tel: loginData.tel.trim(),
              code: loginData.code.trim()
            })).then((response) => {
              const data = response.data
              setToken(data)
              commit('SET_TOKEN', data)
              setUserType('MOBILE_NUMBER_LOGIN')
              commit('SET_USER_TYPE', 'CA')
              resolve(response)
            }).catch((error) => {
              reject(error)
            })
          })
      }
    },

    // 获取用户信息
    GetUserInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo(state.token)
          .then((response) => {
            const data = response.data
            commit('SET_USERINFO', data.userInfo)
            commit('SET_NAME', data.name)
            commit('SET_AVATAR', data.avatar)
            commit('SET_MENUS', data.menus)
            resolve(response)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    // 选择/切换角色
    SelectRole({ commit }, { roleId }) {
      return new Promise((resolve, reject) => {
        selectRole({
          roleId
        })
          .then((response) => {
            const data = response.data
            setToken(data)
            commit('SET_TOKEN', data)
            // 清除tags
            store.dispatch('delAllViews')
            removeStore({
              name: 'tagList'
            })
            resolve(response)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token)
          .then(() => {
            commit('SET_TOKEN', '')
            removeToken()
            // 清除tags
            removeStore({
              name: 'tagList'
            })
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise((resolve) => {
        commit('SET_TOKEN', '')
        removeToken()
        // 清除tags
        removeStore({
          name: 'tagList'
        })
        resolve()
      })
    },

    // 登录
    SetToken({ commit }, data) {
      return new Promise((resolve) => {
        setToken(data)
        commit('SET_TOKEN', data)
        resolve()
      })
    }
  }
}

export default user
